﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using pub.Functions;
using pub.GUI;
using pub.Interop;

namespace scheduler
{
    public partial class MainForm : Form
    {
        private LastWindowState _lastWindowState;
        private bool _quitting;

        public MainForm()
        {
            InitializeComponent();

            _lastWindowState = new LastWindowState(App.Settings["WindowState"], this);

            notifyIcon.Text = this.Text;
            notifyIcon.ContextMenu = this.contextMenu;

            lbTodoList.Font = new Font(SystemFonts.IconTitleFont.FontFamily, 11);
            lbTodoList.MouseDown += lbTodoList_MouseDown;

            var todoLists = App.Scheduler.TodoLists;
            lbTodoList.Items.AddRange(todoLists.ToArray());

            var showOnStartup = App.Settings.ShowOnStartup;
            
            var args = Environment.GetCommandLineArgs();
            this.Visible = showOnStartup || args.Length > 1 && args[1] == "/show";

            for (var n = 1; n < args.Length; n++)
            {
                if (args[n] == "/add")
                {
                    var fileName = args[n + 1];
                    AddTodoList(fileName);
                }
            }

            chkShowOnStartup.Checked = showOnStartup;

            Localize();
        }

        private void Localize()
        {
#if zh
            this.Text = "待办调度器";
            this.btnAdd.Text = "添加(&A)";
            this.btnRemove.Text = "移除(&R)";
            this.btnClose.Text = "关闭(&C)";
            this.mnClose.Text = "关闭(&C)";
            this.mnQuit.Text = "退出(&Q)";
            this.chkShowOnStartup.Text = "启动时显示";
#endif
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if(keyData == (Keys.Control|Keys.Q))
            {
                mnQuit.PerformClick();
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void lbTodoList_MouseDown(object sender, MouseEventArgs e)
        {
            var index = lbTodoList.IndexFromPoint(e.Location);
            if (index == -1)
            {
                lbTodoList.ClearSelected();
            }
        }

        private void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            ShowUp();
        }

        public void ShowUp()
        {
            this.Show();
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            // Activate the form.
            this.Activate();
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
//            if (WindowState == FormWindowState.Minimized)
//            {
//                this.Hide();
//            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing && !_quitting)
            {
                e.Cancel = true;
                this.Hide();
            }
        }

        private void Quit()
        {
            App.Scheduler.SaveChanges();
            _quitting = true;
            this.Close();
            Application.Exit();
        }

        private void lbTodoList_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
            }
        }

        private void lbTodoList_DragDrop(object sender, DragEventArgs e)
        {
            var files = e.Data.GetData(DataFormats.FileDrop, false) as String[];
            AddFiles(files);
        }

        private void AddFiles(params string[] files)
        {
            foreach (var file in files)
            {
                if (App.Scheduler.AddTodoList(file))
                {
                    lbTodoList.Items.Add(file);
                }
            }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            var index = lbTodoList.SelectedIndex;
            if (index == -1)
            {
                return;
            }
            var item = lbTodoList.Items[index] as string;
            App.Scheduler.RemoveTodoList(item);
            lbTodoList.Items.RemoveAt(index);
            if (index > lbTodoList.Items.Count - 1)
            {
                index = lbTodoList.Items.Count - 1;
            }
            if (index >= 0)
            {
                lbTodoList.SelectedIndex = index;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            dlgOpen.DefaultExt = "todolist";
            dlgOpen.Filter = "TodoList files (*.todolist)|*.todolist|All files (*.*)|*.*";
            var result = dlgOpen.ShowDialog();
            if (result != DialogResult.OK)
            {
                return;
            }
            var fileName = dlgOpen.FileName;
            AddFiles(fileName);
        }

        protected override void WndProc(ref Message m)
        {
            if(m.Msg == App.WM_SHOW_MAIN_FORM)
            {
                ShowUp();
            }
            base.WndProc(ref m);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            App.Scheduler.Check();
        }

        private void chkShowOnStartup_CheckedChanged(object sender, EventArgs e)
        {
            App.Settings.ShowOnStartup = chkShowOnStartup.Checked;
        }

        private void mnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void mnQuit_Click(object sender, EventArgs e)
        {
            Quit();
        }

        private void mnQuit2_Click(object sender, EventArgs e)
        {
            Quit();
        }

        public void AddTodoList(string fileName)
        {
            if (!App.Scheduler.ContainsTodoList(fileName))
            {
                var msg = "Add " + fileName + " to scheduler?";
#if zh
                msg = "添加 " + fileName + " 到调度器？";
#endif
                var dr = MessageBox.Show(msg, 
                    App.Title, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if(dr != DialogResult.Yes)
                {
                    return;
                }
            }
            AddFiles(fileName);
            lbTodoList.SelectedItem = fileName;
        }

        private void lbTodoList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var index = lbTodoList.SelectedIndex;
            if (index == -1)
            {
                return;
            }
            var todolist = lbTodoList.Items[index] as string;

            var hwnd = CommonUtils.FindTodoWindowForTodoList(todolist);
            if (hwnd != IntPtr.Zero)
            {
                CommonUtils.ActivateWindow(hwnd);
            }
            else
            {
                Process.Start(todolist);
            }
        }
    }
}